import { z } from 'zod'
import { passwordReg } from './reg'

/**
 * 货币格式
 * @param value
 * @returns
 */
export function currencyFormat(value?: number | string) {
  return value && value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

/**
 * 字节格式
 * @param bytes
 * @param opts
 * @returns
 */
export function byteFormat(
  bytes: number,
  opts: {
    decimals?: number
    sizeType?: 'accurate' | 'normal'
  } = {}
) {
  if (!bytes) return '0 Byte'
  const { decimals = 0, sizeType = 'normal' } = opts

  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const accurateSizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB']
  if (bytes === 0) return '0 Byte'
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return `${(bytes / Math.pow(1024, i)).toFixed(decimals)} ${
    sizeType === 'accurate' ? (accurateSizes[i] ?? 'Bytest') : (sizes[i] ?? 'Bytes')
  }`
}

export function isEmpty(data: unknown) {
  return ['', undefined, null].includes(data as string)
}

/**
 * 表单数据剔除空值（'', undefined, null）
 * @param data
 * @returns
 */
export function filterEmpty<T extends object>(data: T) {
  const newData: Partial<T> = {}

  Object.entries(data).forEach(([key, value]) => {
    if (!isEmpty(value)) {
      newData[key as keyof T] = value
    }
  })

  return newData
}

export function passwordZod(name = '密码') {
  return z
    .string({
      required_error: `${name}不能为空`
    })
    .min(8, `请输入有效的${name}，长度为8-50个字符`)
    .max(50, `请输入有效的${name}，长度为8-50个字符`)
    .refine(d => passwordReg.test(d), `${name}必须包含字母、数字、特殊字符`)
}

export function nameZod(name = '用户名') {
  return z
    .string({
      required_error: `${name}不能为空`
    })
    .min(2, `请输入有效的${name}，长度为2-16字符`)
    .max(16, `请输入有效的${name}，长度为2-16个字符`)
}
